<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <title>Chapter 6: Layouts</title>
    <link rel="stylesheet" type="text/css" href="../css/site.css" />    
    <link rel="stylesheet" type="text/css" href="../css/prettify.css" media="screen" />
    
  </head>
  <body onload="prettyPrint(); decorate();">
    <script type="text/javascript">prefix='../';</script>
    <script type="text/javascript" src="../js/prettify.js"></script>
    <script type="text/javascript" src="../js/dsl.js"></script>
    <script type="text/javascript" src="../js/jquery-min.js"></script>
    <script type="text/javascript" src="../js/decorator.js"></script>

    <div id="container">
      <script type="text/javascript" src="../templates/header.js"></script>
      
      <div id="left">
        <noscript>Please turn on Javascript to view this menu</noscript>
        <script src="../templates/left.js" type="text/javascript"></script>
      </div>
      <div id="right">
        <script src="menu.js" type="text/javascript"></script>
      </div>
    <div id="content">
    
    <h1>Chapter 6: Layouts</h1>

    <a href="layouts_ja.html">&#x548C;&#x8A33; (Japanese translation)</a>
	
    <div class="quote">
      <p>TCP implementations will follow a general principle of
      robustness: be conservative in what you do, be liberal in what
      you accept from others.
      </p>
      <p>&mdash;JON POSTEL, RFC 793</p>
    </div>

    <script src="../templates/creative.js" type="text/javascript"></script>
    <script src="../templates/setup.js" type="text/javascript"></script>
     
		<h2 class="doAnchor">What is a layout?</h2>

		<p>In case you were wondering, layouts have nothing to do with
		large estates in Florida.  Layouts are logback components
		responsible for transforming an incoming event into a String.  The
		<code>format()</code> method in the <a
		href="../xref/ch/qos/logback/core/Layout.html"><code>Layout</code></a>
		interface takes an object that represents an event (of any type)
		and returns a String. A synopsis of the <code>Layout</code>
		interface is shown below.
		</p>

		<pre class="prettyprint source">public interface Layout&lt;E> extends ContextAware, LifeCycle {

  String doLayout(E event);
  String getFileHeader();
  String getPresentationHeader();
  String getFileFooter();
  String getPresentationFooter();
  String getContentType();
}</pre>

		<p>This interface is rather simple and yet is sufficient for many
		formatting needs. The Texan developer from Texas, whom you might
		know from Joseph Heller's <em>Catch-22</em>, might exclaim: it
		just takes five methods to implement a layout!!?
		</p>

		<h2>Logback-classic</h2>

		<p>Logback-classic is wired to process only events of type
		<a href="../xref/ch/qos/logback/classic/spi/ILoggingEvent.html">
      <code>ch.qos.logback.classic.spi.ILoggingEvent</code></a>.  This
			fact will be apparent throughout this section.</p>

		<h2 class="doAnchor" name="writingYourOwnLayout">Writing your own
		custom Layout</h2>

		<p>Let us implement a simple yet functional layout for the
			logback-classic module that prints the time elapsed since the
			start of the application, the level of the logging event, the
			caller thread between brackets, its logger name, a dash followed
			by the event message and a new line.
		</p>

		<p>Sample output might look like:</p>

		<div class="source">10489 DEBUG [main] com.marsupial.Pouch - Hello world.</div>

		<p>Here is a possible implementation, authored by the Texan developer:</p>
		<em>Example: Sample implementation of a Layout
			<a href="../xref/chapters/layouts/MySampleLayout.html">
			(logback-examples/src/main/java/chapters/layouts/MySampleLayout.java)</a></em>

		<pre class="prettyprint source">package chapters.layouts;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.LayoutBase;

public class MySampleLayout extends LayoutBase&lt;ILoggingEvent> {

  public String doLayout(ILoggingEvent event) {
    StringBuffer sbuf = new StringBuffer(128);
    sbuf.append(event.getTimeStamp() - event.getLoggingContextVO.getBirthTime());
    sbuf.append(" ");
    sbuf.append(event.getLevel());
    sbuf.append(" [");
    sbuf.append(event.getThreadName());
    sbuf.append("] ");
    sbuf.append(event.getLoggerName();
    sbuf.append(" - ");
    sbuf.append(event.getFormattedMessage());
    sbuf.append(CoreConstants.LINE_SEP);
    return sbuf.toString();
  }
}</pre>

		<p>Note that <code>MySampleLayout</code> extends <a
		href="../xref/ch/qos/logback/core/LayoutBase.html">
		<code>LayoutBase</code></a>.  This class manages state common to
		all layout instances, such as whether the layout is started or
		stopped, header, footer and content type data. It allows the
		developer to concentrate on the formatting expected from his/her
		<code>Layout</code>. Note that the <code>LayoutBase</code> class
		is generic. In its class declaration, <code>MySampleLayout</code>
		extends <code>LayoutBase&lt;ILoggingEvent&gt;</code>.
		</p>
		
		<p>The <code>doLayout(ILoggingEvent event)</code> method, i.e. the
		only method in <code>MySampleLayout</code>, begins by
		instantiating a <code>StringBuffer</code>. It proceeds by adding
		various fields of the event parameter. The Texan from Texas was
		careful to print the formatted form of the message. This is
		significant if one or more parameters were passed along with
		the logging request.
		</p>
		
    <p>After adding these various characters to the string buffer, the
    <code>doLayout()</code> method converts the buffer into a
    <code>String</code> and returns the resulting value.
		</p>

		<p>In the above example, the <code>doLayout</code> method ignores
		any eventual exceptions contained in the event. In a real world
		layout implementation, you would most probably want to print the
		contents of exceptions as well.
		</p>

    <h3 class="doAnchor" name="configuringYourOwnLayout">Configuring
    your custom layout</h3>

		<p>Custom layouts are configured as any other component. As
		mentioned earlier, <code>FileAppender</code> and its sub-classes
		expect an encoder. In order to fulfill this requirement, we pass
		to <code>FileAppender</code> an instance of
		<code>LayoutWrappingEncoder</code> which wraps our
		<code>MySampleLayout</code>. Here is the configuration file:</p>
		
		<em>Example: Configuration of MySampleLayout
		(logback-examples/src/main/resources/chapters/layouts/sampleLayoutConfig.xml)</em>

<pre id="sampleLayoutConfig" class="prettyprint source">&lt;configuration>

  &lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <b>&lt;encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder"></b>
      <b>&lt;layout class="chapters.layouts.MySampleLayout" /></b>
    <b>&lt;/encoder></b>
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="STDOUT" />
  &lt;/root>
&lt;/configuration></pre>
   
		<p>The sample application <a
		href="../xref/chapters/layouts/SampleLogging.html">
		<code>chapters.layouts.SampleLogging</code></a> configures logback
		with the configuration script passed as its first argument and
		then logs a debug message, followed by an error message. </p>
		
		<p>To run this example issue the following command from within the
		<em>logback-examples</em> directory.
    </p>
    
    <p class="command">java chapters.layouts.SampleLogging src/main/java/chapters/layouts/sampleLayoutConfig.xml</p>
    
    <p> This will produce:</p>
		
<div class="source"><pre>0 DEBUG [main] chapters.layouts.SampleLogging - Everything's going well
0 ERROR [main] chapters.layouts.SampleLogging - maybe not quite...</pre></div>

		<p>That was simple enough.  The skeptic Pyrrho of Elea, who
		insists that nothing is certain except perhaps uncertainty itself,
		which is by no means certain either, might ask: how about a layout
		with options?  The reader shall find a slightly modified version
		of our custom layout in <a
		href="../xref/chapters/layouts/MySampleLayout2.html"><code>MySampleLayout2.java</code></a>. As
		mentioned throughout this manual, adding a property to a layout or
		any other logback component is as simple as declaring a setter
		method for the property.
		</p>

		<p>The <a
		href="../xref/chapters/layouts/MySampleLayout2.html"><code>MySampleLayout2</code></a>
		class contains two properties. The first one is a prefix that can
		be added to the output. The second property is used to choose
		whether to display the name of the thread from which the logging
		request was sent.
    </p>
		
    <p>Here is a copy of the <a
    href="../xref/chapters/layouts/MySampleLayout2.html"><code>MySampleLayout2</code></a>
    class :</p>

    <pre class="prettyprint source">package chapters.layouts;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.LayoutBase;

public class MySampleLayout2 extends LayoutBase&lt;ILoggingEvent> {

  String prefix = null;
  boolean printThreadName = true;

  <b>public void setPrefix(String prefix) {
    this.prefix = prefix;
  }

  public void setPrintThreadName(boolean printThreadName) {
    this.printThreadName = printThreadName;
  }</b>

  public String doLayout(ILoggingEvent event) {
    StringBuffer sbuf = new StringBuffer(128);
    <b>if (prefix != null) {
      sbuf.append(prefix + ": ");
    }</b>
    sbuf.append(event.getTimeStamp() - event.getLoggerContextVO().getBirthTime());
    sbuf.append(" ");
    sbuf.append(event.getLevel());
    <b>if (printThreadName) {
      sbuf.append(" [");
      sbuf.append(event.getThreadName());
      sbuf.append("] ");
    } else {
      sbuf.append(" ");
    }</b>
    sbuf.append(event.getLoggerName());
    sbuf.append(" - ");
    sbuf.append(event.getFormattedMessage());
    sbuf.append(LINE_SEP);
    return sbuf.toString();
  }
}</pre>


    <p>The addition of the corresponding setter method is all that is
    needed to enable the configuration of a property.  Note that the
    <code>PrintThreadName</code> property is a boolean and not a
    <code>String</code>. Configuration of logback components was
    covered in detail in the <a
    href="configuration.html">chapter on configuration</a>. The <a
    href="onJoran.html">chapter on Joran</a> provides further detail. Here is
    the configuration file tailor made for
    <code>MySampleLayout2</code>.
    </p> 


    <pre id="MySampleLayout2" class="prettyprint source">&lt;configuration>

  &lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    &lt;encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
      &lt;layout class="chapters.layouts.MySampleLayout2"> 
        <b>&lt;prefix&gt;MyPrefix&lt;/prefix&gt;</b>
        <b>&lt;printThreadName&gt;false&lt;/printThreadName&gt;</b>
      &lt;/layout>
    &lt;/encoder>
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="STDOUT" />
  &lt;/root>
&lt;/configuration></pre>

   <p></p>


     <h2 class="doAnchor" name="ClassicPatternLayout">PatternLayout</h2>

     <p>Logback classic ships with a flexible layout called <a
     href="../xref/ch/qos/logback/classic/PatternLayout.html">
     <code>PatternLayout</code></a>.  As all layouts,
     <code>PatternLayout</code> takes a logging event and returns a
     <code>String</code>. However, this <code>String</code> can be
     customized by tweaking <code>PatternLayout</code>'s conversion
     pattern.
     </p>   

    <p>The conversion pattern of <code>PatternLayout</code> is closely
    related to the conversion pattern of the <code>printf()</code>
    function in the C programming language. A conversion pattern is
    composed of literal text and format control expressions called
    <em>conversion specifiers</em>. You are free to insert any literal
    text within the conversion pattern. Each conversion specifier
    starts with a percent sign '%' and is followed by optional
    <em>format modifiers</em>, a <em>conversion word</em> and optional
    parameters between braces. The conversion word controls the data
    field to convert, e.g. logger name, level, date or thread
    name. The format modifiers control field width, padding, and left
    or right justification.
    </p>

    <p>As already mentioned on several occasions,
    <code>FileAppender</code> and sub-classes expect an
    encoder. Consequently, when used in conjunction with
    <code>FileAppender</code> or its subclasses a
    <code>PatternLayout</code> must be wrapped within an
    encoder. Given that the
    <code>FileAppender</code>/<code>PatternLayout</code> combination
    is so common, logback ships with an encoder named
    <code>PatternLayoutEncoder</code>, designed solely for the purpose
    of wrapping a <code>PatternLayout</code> instance so that it can
    be seen as encoder. Below is an example which programmatically
    configures a <code>ConsoleAppender</code> with a
    <code>PatternLayoutEncoder</code>:</p>

 
    <em>
      Example: Sample usage of a PatternLayout
      <a href="../xref/chapters/layouts/PatternSample.html">
      (logback-examples/src/main/java/chapters/layouts/PatternSample.java)</a>
    </em>
    <pre class="prettyprint source">package chapters.layouts;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;

public class PatternSample {

  static public void main(String[] args) throws Exception {
    Logger rootLogger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    LoggerContext loggerContext = rootLogger.getLoggerContext();
    // we are not interested in auto-configuration
    loggerContext.reset();

    <b>PatternLayoutEncoder encoder = new PatternLayoutEncoder();</b>
    <b>encoder.setContext(loggerContext);</b>
    <b>encoder.setPattern("%-5level [%thread]: %message%n");</b>
    <b>encoder.start();</b>

    ConsoleAppender&lt;ILoggingEvent> appender = new ConsoleAppender&lt;ILoggingEvent>();
    appender.setContext(loggerContext);
    appender.setEncoder(encoder); 
    appender.start();

    rootLogger.addAppender(appender);

    rootLogger.debug("Message 1"); 
    rootLogger.warn("Message 2");
  } 
}</pre>

		<p>In the above example, the conversion pattern is set to be
		<b>"%-5level [%thread]: %message%n"</b>. A synopsis of conversion
		word included in logback will be given shortly. Running
		<code>PatternSample</code> application as:
		</p>

    <p class="source">java java chapters.layouts.PatternSample</p>

    <p>will yield the following		output on the console.</p>

		<p class="source">DEBUG [main]: Message 1 
WARN  [main]: Message 2</p>

    <p>Note that in the conversion pattern <b>"%-5level [%thread]:
    %message%n"</b> there is no explicit separator between literal
    text and conversion specifiers. When parsing a conversion pattern,
    <code>PatternLayout</code> is capable of differentiating between
    literal text (space characters, the brackets, colon character) and
    conversion specifiers. In the example above, the conversion
    specifier %-5level means the level of the logging event should be
    left justified to a width of five characters. Format specifiers
    will be explained below.
		</p>

		<p>In <code>PatternLayout</code>, parenthesis can be used to group
		conversion patterns. <b>It follows that the '(' and ')' carry
		special meaning and need to be escaped if intended to be used as
		literals. </b> The special nature of parenthesis is further <a
		href="#Parentheses">explained below</a>.
		</p>

		<p>As mentioned previously, certain conversion specifiers may
		include optional parameters passed between braces. A sample
		conversion specifier with options could be
		<code>%logger{10}</code>. Here "logger" is the conversion word,
		and 10 is the option. Options are <a href="#cwOptions">further
		discussed below</a>.
		</p>
		
		<p>The recognized conversions words along with their options are
		described in the table below. When multiple conversion words are
		listed in the same table cell, they are considered as aliases.
		</p>

		<table class="bodyTable properties striped" border="0">
      <tr>
        <th><a name="conversionWord" href="#conversionWord">Conversion Word</a></th>
        <th>Effect</th>
      </tr>

			<tr>
				<td class="word" name="logger">
          <a name="logger" href="#logger"><span class="anchor"/></a>
					<b>c</b>{<em>length</em>} <br /> 				
					<b>lo</b>{<em>length</em>} <br />
					<b>logger</b>{<em>length</em>} <br />
				</td>

				<td>
          Outputs the name of the logger at the origin of the logging
          event.

					<p>This conversion word takes an integer as its first and
					only option. The converter's abbreviation algorithm will
					shorten the logger name, usually without significant loss of
					meaning. Setting the value of length option to zero
					constitutes an exception. It will cause the conversion word
					to return the sub-string right to the rightmost dot
					character in the logger name. The next table provides
					examples of the abbreviation algorithm in action.
          </p>

					<table class="bodyTable dark" border="0" cellpadding="8">
						<tr>
							<th>Conversion specifier</th>
							<th>Logger name</th>
							<th>Result</th>
						</tr>
						<tr>
							<td>%logger</td>
							<td>mainPackage.sub.sample.Bar</td>
							<td>mainPackage.sub.sample.Bar</td>
						</tr>

            <tr>
							<td>%logger{0}</td>
							<td>mainPackage.sub.sample.Bar</td>
							<td>Bar</td>
						</tr>

						<tr>
							<td>%logger{5}</td>
							<td>mainPackage.sub.sample.Bar</td>
							<td>m.s.s.Bar</td>
						</tr>

						<tr>
							<td>%logger{10}</td>
							<td>mainPackage.sub.sample.Bar</td>
							<td>m.s.s.Bar</td>
						</tr>

						<tr>
							<td>%logger{15}</td>
							<td>mainPackage.sub.sample.Bar</td>
							<td>m.s.sample.Bar</td>
						</tr>

						<tr>
							<td>%logger{16}</td>
							<td>mainPackage.sub.sample.Bar</td>
							<td>m.sub.sample.Bar</td>
						</tr>

						<tr>
							<td>%logger{26}</td>
							<td>mainPackage.sub.sample.Bar</td>
							<td>mainPackage.sub.sample.Bar</td>
						</tr>
					</table>

          <p>Please note that the rightmost segment in a logger name
          is never abbreviated, even if its length is longer than the
          <em>length</em> option. Other segments may be shortened to
          at most a single character but are never removed.</p>

				</td>
			</tr>

			<tr>
				<td class="word" name="class">
					<b>C</b>{<em>length</em>} <br /> 
					<b>class</b>{<em>length</em>} <br />
				</td>

				<td>
					<p>Outputs the fully-qualified class name of the caller
					issuing the logging request.
					</p>

					<p>Just like the <em>%logger</em> conversion word above,
					this conversion takes an integer as an option to shorten
					the class name. Zero carries special meaning and will cause
					the simple class name to be printed without the package name
					prefix. By default the class name is printed in full.
					</p>

          <p>Generating the caller class information is not
          particularly fast.  Thus, its use should be avoided unless
          execution speed is not an issue.
					</p>
				</td>
			</tr>

      <tr>
        <td class="word" name="contextName">
          <b>contextName</b><br/>
          <b>cn</b><br/></td>
          <td>Outputs the name of the logger context to which the
          logger at the origin of the event was attached to. </td>
      </tr>
      <tr>
        <td class="word" name="date">
          <b>d</b>{<em>pattern</em>} <br /> 
          <b>date</b>{<em>pattern</em>} <br />
          <b>d</b>{<em>pattern</em>, <em>timezone</em>} <br />
          <b>date</b>{<em>pattern</em>,&nbsp;<em>timezone</em>} <br />
        </td>
        <td>
         <p>Used to output the date of the logging event.  The date
         conversion word admits a pattern string as a parameter. The
         pattern syntax is compatible with the format accepted by <a
         href="https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html"><code>java.text.SimpleDateFormat</code></a>
         (in logback 1.2.x) and <a
         href="https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html">java.time.format.DateTimeFormatter</a>
         (in logback 1.3.x). </p>
         
         <p>You can specify the string <em>"ISO8601"</em> for the
         ISO8601 date format. Note that the %date conversion word
         defaults to the <a
         href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601 date
         format</a> in the absence of a pattern parameter.</p>
         
         <p>Here are some sample parameter values. They assume that
         the actual date is Friday 20th of October, 2006 and that the
         author has returned to working on this document just after
         lunch.</p>
					
         <table class="bodyTable dark" cellpadding="8">
           <tr>
             <th>Conversion Pattern</th>
            <th>Result</th>
           </tr>
           <tr>
             <td>%d</td>
             <td>2006-10-20 14:06:49,812</td>
           </tr>
           <tr>
             <td>%date</td>
             <td>2006-10-20 14:06:49,812</td>
           </tr>
           <tr>
             <td>%date{ISO8601}</td>
             <td>2006-10-20 14:06:49,812</td>
           </tr>			
           <tr>
             <td>%date{HH:mm:ss.SSS}</td>
             <td>14:06:49.812</td>
           </tr>
           <tr>
             <td>%date{dd&nbsp;MMM&nbsp;yyyy;HH:mm:ss.SSS}</td>
             <td>20 oct. 2006;14:06:49.812	</td>
           </tr>
         </table>
         
          <p>The second parameter specifies a timezone. For example,
          the '%date{HH:mm:ss.SSS,&nbsp;Australia/Perth} would print
          the time in the time zone of Perth, Australia, the world's
          most isolated city.  Note that in the absence of the
          timezone parameter, the default timezone of the host Java
          platform is used.  If the specified timezone identifier is
          unknown or misspelled, the GMT timezone is assumed as
          dictated by the <a
          href="http://docs.oracle.com/javase/6/docs/api/java/util/TimeZone.html#getTimeZone(java.lang.String)">TimeZone.getTimeZone(String)</a>
          method specification.
          </p>


          If the option includes special characters such as a braces, spaces or commas, you can enclose it between single or double quotes.
          
          <p><span class="label">common error</span> Given that the
          comma ',' character is interpreted as the parameter
          separator, the pattern <code>HH:mm:ss,SSS</code> will be
          interpreted as the pattern <code>HM:mm:ss</code> and the
          timezone <code>SSS</code>. If you wish to include a comma in
          your date pattern, then simply enclose the pattern between
          single or double quotes. For example,
          %date{<b>"</b>HH:mm:ss,SSS<b>"</b>} or
          %date{<b>'</b>HH:mm:ss,SSS<b>'</b>}.
          </p>
	</td>
         </tr>

        <tr>
          <td class="word" name="micros">
            <b>micros / ms</b>
          </td>
          <td><p><span class="label notice">Since 1.3</span> Outputs the microseconds of the timestamp included in
          the event.</p>

          <p>For performacne reasons, the microseconds have to be specified separately and in addition to %date.</p>
          </td>
        </tr>

      
                        
			<tr>
				<td class="word" name="file">
					<b>F / file</b>
				</td>

				<td>
					<p>Outputs the file name of the Java source file where the
					logging request was issued.
					</p>

					<p>Generating the file information is not particularly fast.
					Thus, its use should be avoided unless execution speed is
					not an issue.
					</p>
				</td>
			</tr>

			<tr >
				<td class="word" name="caller">
					<b>caller{depth}</b>
					<b>caller{depthStart..depthEnd}</b>
					<b>caller{depth, evaluator-1, ... evaluator-n}</b>
					<b>caller{depthStart..depthEnd, evaluator-1, ... evaluator-n}</b>
				</td>

				<td>
					<p>Outputs location information of the caller which
					generated the logging event.
					</p>

					<p>The location information depends on the JVM
					implementation but usually consists of the fully qualified
					name of the calling method followed by the caller's source,
					the file name and line number between parentheses.
					</p>

					<p>A integer can be added to the <em>caller</em> conversion
					specifier's options to configure the depth of the
					information to be displayed.
					</p>

          <p>For example, <b>%caller{2}</b> would display the
          following excerpt:</p>
					
<pre class="source white_bg">0    [main] DEBUG - logging statement 
Caller+0   at mainPackage.sub.sample.Bar.sampleMethodName(Bar.java:22)
Caller+1   at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17)</pre>

					<p>And <b>%caller{3}</b> would display this other excerpt:</p>

<pre class="source white_bg">16   [main] DEBUG - logging statement 
Caller+0   at mainPackage.sub.sample.Bar.sampleMethodName(Bar.java:22)
Caller+1   at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17)
Caller+2   at mainPackage.ConfigTester.main(ConfigTester.java:38)</pre>

                    <p>A range specifier can be added to the <em>caller</em> conversion specifier's
                    options to configure the depth range of the information to be displayed.
                    </p>

                    <p>For example, <b>%caller{1..2}</b> would display the following excerpt:</p>

<pre class="source white_bg">0    [main] DEBUG - logging statement
Caller+0   at mainPackage.sub.sample.Bar.createLoggingRequest(Bar.java:17)</pre>

					<p>This conversion word can also use evaluators to test
					logging events against a given criterion before computing
					caller data. For example, using <b>%caller{3,
					CALLER_DISPLAY_EVAL}</b> will display three lines of
					stacktrace, only if the evaluator called
					<em>CALLER_DISPLAY_EVAL</em> returns a <b>positive</b>
					answer.
				</p>

				 <p>Evaluators are described below.</p>
				</td>
			</tr>

		<tr>
		  <td class="word" name="kvp">
		    <b>kvp{NONE,SINGLE,DOUBLE}</b>
		  </td>
		  <td>
                    <p>Outputs the key value pairs contained in the
                    logging event. By default, the value part will be
                    surrounded by double quotes. You can
                    override the default by specifying NONE or SINGLE,
                    for no quote character or the single quote
                    character &apos; respectively.                    
                    </p>

                    <p>The value key pairs {k1, v1} and {k2, v2}
                    contained in the event will be output as follows:
                    <table>
                      <tr>
                        <td>NONE</td>
                        <td>v1=k1 v2=k2</td>
                      </tr>
                      <tr>
                        <td>DOUBLE</td>
                        <td>v1="k1" v2="k2"</td>
                      </tr>
                      <tr>
                        <td>SINGLE</td>
                        <td>v1='k1' v1='k1'</td>
                      </tr>
                      <tr>
                        <td>default</td>
                        <td>same as if DOUBLE were specified</td>
                      </tr>
                      
                    </table>
		  </td>
		</tr>

                        
		<tr>
		  <td class="word" name="line">
		    <b>L / line</b>
		  </td>
                  
		  <td><p>Outputs the line number from where the logging
		  request was issued.</p>
                  
		  <p>Generating the line number information is not
		  particularly fast.  Thus, its use should be avoided unless
		  execution speed is not an issue.
		  </p>
		  </td>
		</tr>

                
		<tr>
		  <td class="word" name="message">
		    <b>m / msg / message</b>
		  </td>
		  <td>
                    <p>Outputs the application-supplied message associated with
                    the logging event.
                    </p>
		  </td>
		</tr>

		<tr>
		  <td class="word" name="method">
		    <b>M / method</b>
		  </td>

		  <td>
		    <p>Outputs the method name where the logging request was
		    issued.</p>
		    <p>Generating the method name is not particularly fast.
		    Thus, its use should be avoided unless execution speed is
		    not an issue.</p>
		  </td>
		</tr>
                
		<tr>
		  <td class="word" name="newline">
		    <b>n</b>
		  </td>
                  
		  <td>
		    <p>Outputs the platform dependent line separator
		    character or characters.</p>
		    <p>This conversion word offers practically the same
		    performance as using non-portable line separator strings
		    such as "\n", or "\r\n". Thus, it is the preferred way of
		    specifying a line separator.
		    </p>
		  </td>

			</tr>

			<tr>
				<td class="word" name="level">
					<b>p / le / level</b>
				</td>
				<td>Outputs the level of the logging event.</td>
			</tr>

			<tr>

				<td class="word" name="relative">
					<b>r / relative</b>
				</td>

				<td>Outputs the number of milliseconds elapsed since the start
				of the application until the creation of the logging event.
				</td>
			</tr>


			<tr>
				<td class="word" name="relative">
					<b>t / thread</b>
				</td>

				<td>Outputs the name of the thread that generated the logging
				event.
				</td>

			</tr>

			<tr>
				<td class="word" name="mdc">
					<b>X</b>{<em>key:-defaultVal</em>} <br /> 
					<b>mdc</b>{<em>key:-defaultVal</em>} <br />
				</td>

				<td>

					<p>Outputs the MDC (mapped diagnostic context) associated
					with the thread that generated the logging event.
					</p>

					<p>If the <b>mdc</b> conversion word is followed by a key
					between braces, as in <b>%mdc{userid}</b>, then the MDC
					value corresponding to the key 'userid' will be output. If
					the value is null, then the <a
					href="configuration.html#defaultValuesForVariables">default
					value</a> specified after the <b>:-</b> operator is
					output. If no default value is specified than the empty
					string is output.
					</p>

					<p>If no key is given, then the entire content of the MDC
					will be output in the format "key1=val1, key2=val2".
					</p>

					<p>See the <a href="mdc.html">chapter on MDC</a> for more
					details on the subject.</p>

				</td>
			</tr>
			<tr>
				<td class="word" name="ex">
					<b>ex</b>{<em>depth</em>} <br /> 
          	<b>exception</b>{<em>depth</em>} <br /> 
					<b>throwable</b>{<em>depth</em>} <br />
          <br />
					<b>ex</b>{depth, evaluator-1, ..., evaluator-n} <br />
					<b>exception</b>{depth, evaluator-1, ..., evaluator-n} <br />
					<b>throwable</b>{depth, evaluator-1, ..., evaluator-n}
				</td>

				<td>
					<p>Outputs the stack trace of the exception
					associated with the logging event, if any. By default the
					full stack trace will be output.
				 </p>
         

  			 <p>The <em>throwable</em> conversion word can followed by one of
						the following options:
				 </p>
				 <ul>
				   <li><em>short</em>: prints the first line of the stack trace</li>
				   <li><em>full</em>: prints the full stack trace</li>
				   <li>Any integer: prints the given number of lines of the stack trace</li>
				 </ul>
				 
				 <p>Here are some examples:</p>
				 
				 <table  class="bodyTable">
						<tr class="a">
							<th>Conversion Pattern</th>
							<th>Result</th>
						</tr>
						<tr class="b">
							<td>%ex</td>
							<td><pre>mainPackage.foo.bar.TestException: Houston we have a problem
  at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)
  at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17)
  at mainPackage.ExceptionLauncher.main(ExceptionLauncher.java:38)</pre></td>
						</tr>
						<tr class="a">
							<td>%ex{short}</td>
							<td><pre>mainPackage.foo.bar.TestException: Houston we have a problem
  at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)</pre></td>
						</tr>
						<tr class="b">
							<td>%ex{full}</td>
							<td><pre>mainPackage.foo.bar.TestException: Houston we have a problem
  at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)
  at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17)
  at mainPackage.ExceptionLauncher.main(ExceptionLauncher.java:38)</pre></td>
						</tr>
						<tr class="a">
							<td>%ex{2}</td>
							<td><pre>mainPackage.foo.bar.TestException: Houston we have a problem
  at mainPackage.foo.bar.TestThrower.fire(TestThrower.java:22)
  at mainPackage.foo.bar.TestThrower.readyToLaunch(TestThrower.java:17)</pre></td>
						</tr>
				 </table>
					
	<p>This conversion word can also use evaluators to test
	logging events against a given criterion before creating the
	output. For example, using <b>%ex{full, EX_DISPLAY_EVAL}</b>
	will display the full stack trace of the exception only if the
	evaluator called <em>EX_DISPLAY_EVAL</em> returns a
	<b>negative</b> answer. Evaluators are described further down
	in this document.
	</p>

         <p>If you do not specify %throwable or another
          throwable-related conversion word in the conversion pattern,
          <code>PatternLayout</code> will automatically add it as the
          last conversion word, on account of the importance of stack
          trace information. The $nopex conversion word can be
          substituted for %throwable, if you do not wish stack trace
          information to be displayed. See also the %nopex conversion
          word.
         </p>
         
	</td>
      </tr>
      
      <tr>
	<td class="word" name="xThrowable">
	  <b>xEx</b>{<em>depth</em>} <br /> 
          <b>xException</b>{<em>depth</em>} <br /> 
					<b>xThrowable</b>{<em>depth</em>} <br />
          <br />
					<b>xEx</b>{depth, evaluator-1, ..., evaluator-n} <br />
					<b>xException</b>{depth, evaluator-1, ..., evaluator-n} <br />
					<b>xThrowable</b>{depth, evaluator-1, ..., evaluator-n}
				</td>

				<td>
					<p>Same as the %throwable conversion word above with the
					addition of class packaging information.</p>

          <p>At the end of each stack frame of the exception, a string
          consisting of the jar file containing the relevant class
          followed by the "Implementation-Version" as found in that
          jar's manifest will be added. This innovative technique was
          <a
          href="http://macstrac.blogspot.com/2008/09/better-stack-traces-in-java-with-log4j.html">originally suggested
          by James Strachan</a>. If the information is uncertain, then
          the class packaging data will be preceded by a tilde, i.e.
          the '~' character.
          </p>

          <p>Here is an example:</p>

          <p class="source small">java.lang.NullPointerException
  at com.xyz.Wombat(Wombat.java:57) <b><span class="red">~</span>[wombat-1.3.jar:1.3]</b>
  at  com.xyz.Wombat(Wombat.java:76) ~[wombat-1.3.jar:1.3]
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.5.0_06]
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.5.0_06]
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.5.0_06]
  at java.lang.reflect.Method.invoke(Method.java:585) ~[na:1.5.0_06]
  at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59) [junit-4.4.jar:na]
  at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98) [junit-4.4.jar:na]
  ...etc </p>

          <p>Logback goes to great lengths to ensure that the class
          packaging information it displays is correct, even in
          arbitrarily complex class loader hierarchies.  However, when
          it is unable to guarantee the absolute correctness of the
          information, then it will prefix the data with a tilde, i.e.
          the '~' character. Thus, it is theoretically possible for
          the printed class packaging information to differ from the
          real class packaging information. So, in the above example,
          given that packaging data for the Wombat class is preceded
          by a tilde, it is possible that the correct packaging data is
          in reality [wombat.jar:1.7].
          </p>

          <p>Please note that given its potential cost, computation of
          <a href="configuration.html#packagingData"><b>packaging data
          is disabled by default</b></a>. When computation of
          packaging data is enabled, <code>PatternLayout</code> will
          automatically assume the %xThrowable suffix instead of
          %throwable suffix at the end of the pattern string.</p>

          <p><a
          href="http://jira.qos.ch/browse/LBCLASSIC-212">Feedback from
          users</a> indicates that Netbeans chokes on packaging
          information.
          </p>
        </td>

      </tr>

      <tr>
        <td class="word" name="nopex">
          <b>nopex</b> <br />
          <b>nopexception</b>
        </td>

        <td>
          <p>Although it <em>pretends</em> to handle stack trace data,
          this conversion word does not output any data, thus,
          effectively ignoring exceptions.
          </p>

          <p>The %nopex conversion word allows the user to override
          <code>PatternLayout</code>'s internal safety mechanism which
          silently adds the %xThrowable conversion keyword in the absence of
          another conversion word handling exceptions.
          </p>
        </td>
      </tr>

      <tr >
        <td class="word" name="marker">
          <b>marker</b>
        </td>

        <td>
          <p>Outputs the marker associated with the logger 
         request.</p>

          <p>In case the marker contains children markers, the
          converter displays the parent as well as childrens' names
          according to the format shown below.
          </p>
          <p>
            <em>parentName [ child1, child2 ]</em>
          </p>
        </td>
      </tr>


      <tr>
        <td class="word" name="property">
          <b>property{key}</b>
        </td>
        
        <td><p>Outputs the value associated with a property named
        <em>key</em>. The the relevant docs on how to define ion
        entitled <a
        href="configuration.html#variableSubstitution">define
        variables</a> and <a href="configuration.html#scopes">variable
        scopes</a>. 

        <!-- XXXXXXXXXXXX -->

        If <em>key</em> is not a property of
        the logger context, then <em>key</em> will be looked up in the
        System properties.</p>


         <p>There is no default value for <em>key</em>. If it is
         omitted, the returned value will be "Property_HAS_NO_KEY",
         expliciting the error condition.</p>
          
        </td>
      </tr>

      <tr>
        <td class="word" name="replace">
          <b>replace(<em>p</em>){r, t}</b>
        </td>
        
        <td>
          <p>Replaces occurrences of 'r', a regex, with its
          replacement 't' in the string produces by the sub-pattern
          'p'. For example, "%replace(%msg){'\s', ''}" will remove all
          spaces contained in the event message. 
          </p>

          <p>The pattern 'p' can be arbitrarily complex and in
          particular can contain multiple conversion keywords. For
          instance, "%replace(%logger %msg){'\.', '/'}" will replace
          all dots in the logger or the message of the event with a
          forward slash.
          </p>
          
        </td>
      </tr>

      <tr>
        <td class="word" name="prefix">
          <b>prefix(<em>p</em>)</b>
        </td>
        
        <td><p>For all the child converters contained in pattern 'p',
        prefixes the output of each converter with the name of the
        converter.  In environments where log contents need to be
        analysed, it is often useful to prefix the contents of a
        pattern with a prefix.</p>

        <p>For example, you may wish to use the following pattern to
        facilitate parsing of log files:
        </p>

        <pre>%d thread=%thread level=%level logger=%logger user=%X{user} %message</pre>

        <p>The %prefix composite converter can take care of the prefixing for you:
        
        <pre>%d <b>%prefix(</b>%thread %level %logger %X{user}<b>)</b> %message</pre>

        <p>The two previous patterns will generate equivalent
        output. The usefullness of the %prefix converter increases
        with the number of child converters contained in the pattern
        'p'.</p>
        
        </td>
      </tr>


      <tr>
        <td class="word" name="rootException">
          <b>rEx</b>{<em>depth</em>} <br /> 
          <b>rootException</b>{<em>depth</em>} <br /> 
          <br />
	  <b>rEx</b>{depth, evaluator-1, ..., evaluator-n} <br />
	  <b>rootException</b>{depth, evaluator-1, ..., evaluator-n}
        </td>
        
        <td>
          <p>Outputs the stack trace of the exception associated with
          the logging event, if any. The root cause will be output
          first instead of the standard "root cause last". Here is a
          sample output (edited for space):
          </p>

         <pre class="small">java.lang.NullPointerException
  at com.xyz.Wombat(Wombat.java:57) ~[wombat-1.3.jar:1.3]
  at com.xyz.Wombat(Wombat.java:76) ~[wombat-1.3.jar:1.3]
Wrapped by: org.springframework.BeanCreationException: Error creating bean with name 'wombat': 
  at org.springframework.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248) [spring-2.0.jar:2.0]
  at org.springframework.AbstractBeanFactory.getBean(AbstractBeanFactory.java:170) [spring-2.0.jar:2.0]
  at org.apache.catalina.StandardContext.listenerStart(StandardContext.java:3934) [tomcat-6.0.26.jar:6.0.26]
</pre>          

         <p>The %rootException converter admits the same optional
         parameters as the %xException converter described above,
         including depth and evaluators. It outputs also packaging
         information. In short, %rootException is very similar to
         %xException, only the order of exception output is reversed.
         </p>

         <p>Tomasz Nurkiewicz, the author of %rootException converter,
         documents his contribution in a blog entry entitled <a
         href="http://nurkiewicz.blogspot.com/2011/09/logging-exceptions-root-cause-first.html">"Logging
         exceptions root cause first"</a>.</p>
        </td>
      </tr>

		</table>


    <h4 class="doAnchor" name="percentIsSpecial">% character has special meaning</h4>

    <p>Given that in the context of conversion patterns the percent
    sign carries special meaning, in order to include it as a literal,
    it needs to be escaped with a backslash, e.g. "%d %p <b>\%</b>
    %m%n".
    </p>

    <h4 class="doAnchor" name="restrictionsOnLiterals">Restrictions on
    literals immediately following conversion words</h4>

    <p>In most cases literals naturally contain spaces or other
    delimiting characters so that they are not confused with
    conversion words. For example, the pattern
    "%level&nbsp;[%thread]&nbsp;-&nbsp;%message%n" contains the string
    literals <code>"&nbsp;["</code> and
    <code>"]&nbsp;-&nbsp;"</code>. However, if a character which can
    be part of a java identifier immediately follows a conversion
    word, logback's pattern parser will be fooled into thinking that
    the literal is part of the conversion word. For example, the
    pattern "%date<b>%nHello</b>" will be interpreted as two
    conversion words %date and %nHello and since %nHello is not a
    known conversion word, logback will output %PARSER_ERROR[nHello]
    for %nHello. If you wish the string literal "Hello" to immediately
    separate %n and Hello, pass an empty argument list to %n. For
    example, "%date<b>%n{}</b>Hello" will be interpreted as %date
    followed by %n followed by the literal "Hello".

    </p>

    <h2 class="doAnchor" name="formatModifiers">Format modifiers</h2>

		<p>By default the relevant information is output as-is.  However,
		with the aid of format modifiers it is possible to change the
		minimum and maximum width and the justifications of each data
		field.
		</p>

		<p>The optional format modifier is placed between the percent sign
		and the conversion character or word.
		</p>

		<p>The first optional format modifier is the <em>left
		justification flag</em> which is just the minus (-)
		character. Then comes the optional <em>minimum field width</em>
		modifier. This is a decimal constant that represents the minimum
		number of characters to output. If the data item contains fewer
		characters, it is padded on either the left or the right until the
		minimum width is reached. The default is to pad on the left (right
		justify) but you can specify right padding with the left
		justification flag. The padding character is space. If the data
		item is larger than the minimum field width, the field is expanded
		to accommodate the data. The value is never truncated.
		</p>

		<p>This behavior can be changed using the <em>maximum field
		width</em> modifier which is designated by a period followed by a
		decimal constant. If the data item is longer than the maximum
		field, then the extra characters are removed from the
		<em>beginning</em> of the data item. For example, if the maximum
		field width is eight and the data item is ten characters long,
		then the first two characters of the data item are dropped. This
		behavior deviates from the printf function in C where truncation
		is done from the end.
		</p>

		<p>Truncation from the end is possible by appending a minus
		character right after the period. In that case, if the maximum
		field width is eight and the data item is ten characters long,
		then the last two characters of the data item are dropped.
		</p>

		<p>Below are various format modifier examples for the logger
		conversion specifier.
		</p>

		<table class="bodyTable" border="0" cellpadding="8">
      <tr>
        <th>Format modifier</th>
        <th>Left justify</th>
        <th>Minimum width</th>
        <th>Maximum width</th>
        <th>Comment</th>
      </tr>
			<tr class="a">
				<td align="center">%20logger</td>
				<td align="center">false</td>
				<td align="center">20</td>
				<td align="center">none</td>
				<td>
					Left pad with spaces if the logger name is less
					than 20 characters long.
				</td>
			</tr>
			<tr class="b">
				<td align="center">%-20logger</td>
				<td align="center">true</td>
				<td align="center">20</td>
				<td align="center">none</td>
				<td>
					Right pad with spaces if the logger name is less
					than 20 characters long.
				</td>
			</tr>
			<tr class="a">
				<td align="center">%.30logger</td>
				<td align="center">NA</td>
				<td align="center">none</td>
				<td align="center">30</td>
				<td>
					Truncate from the beginning if the logger name is
					longer than 30 characters.
				</td>
			</tr>
			<tr class="b">
				<td align="center">%20.30logger</td>
				<td align="center">false</td>
				<td align="center">20</td>
				<td align="center">30</td>
				<td>
					Left pad with spaces if the logger name is shorter
					than 20 characters. However, if logger name is
					longer than 30 characters, then truncate from the
					beginning.
				</td>
			</tr>
			<tr class="a">
				<td align="center">%-20.30logger</td>
				<td align="center">true</td>
				<td align="center">20</td>
				<td align="center">30</td>
				<td>
					Right pad with spaces if the logger name is shorter
					than 20 characters. However, if logger name is
					longer than 30 characters, then truncate from the
					<em>beginning</em>.
				</td>
			</tr>
			<tr class="b">
				<td align="center">%.-30logger</td>
				<td align="center">NA</td>
				<td align="center">none</td>
				<td align="center">30</td>
				<td>
					Truncate from the <em>end</em> if the logger name is
					longer than 30 characters.
				</td>
			</tr>
		</table>
				
		<p>The table below list examples for format modifier
		truncation. Please note that the square brackets, i.e the pair of "[]"
		characters, are not part of the output. They are used to delimit
		the width of output.</p>


		<table  class="bodyTable" border="0" cellpadding="8">
      <tr>
        <th>Format modifier</th>
        <th>Logger name</th>
        <th>Result</th>		
      </tr>
			<tr class="b">
				<td align="center">[%20.20logger]</td>
				<td align="center">main.Name</td>
				<td align="center"><pre>[           main.Name]</pre></td>
			</tr>
      <tr class="a">
				<td align="center">[%-20.20logger]</td>
				<td align="center">main.Name</td>
				<td align="center"><pre>[main.Name           ]</pre></td>
			</tr>
		  <tr class="a">
				<td align="center">[%10.10logger]</td>
				<td align="center">main.foo.foo.bar.Name</td>
				<td align="center"><pre>[o.bar.Name]</pre></td>
			</tr>
			<tr class="b">
				<td align="center">[%10.-10logger]</td>
				<td align="center">main.foo.foo.bar.Name</td>
				<td align="center"><pre>[main.foo.f]</pre></td>
			</tr>
		</table>

    <h3 class="doAnchor" name="oneLetterLevel">Output just one letter
    for the level</h3>

    <p>Instead of printing TRACE, DEBUG, WARN, INFO or ERROR for the
    level, you may want to print just T, D, W, I and E. You could
    write a <a href="#customConversionSpecifier">custom converter</a>
    for this purpose, or simply make use of format modifiers (just
    discussed) to shorten the level value to a single character. The
    appropriate conversion specifier would be
    "<code>%.-1level</code>".
    </p>
    
		<h2 class="doAnchor" name="cwOptions">Conversion word options</h2>

		<p>A conversion specifier can be followed by options. The are
		always declared between braces. We have already seen some of the
		possibilities offered by options, for instance in conjunction with
		the MDC conversion specifier, as in: <em>%mdc{someKey}</em>.
		</p>

    <p>A conversion specifier might have more than one option. For
    example, a conversion specifier that makes use of evaluators,
    which will be covered soon, may add evaluator names to the option
    list, as shown below:</p>

		<pre class="prettyprint source">&lt;pattern>%-4relative [%thread] %-5level - %msg%n \
  <b>%caller{2, DISP_CALLER_EVAL, OTHER_EVAL_NAME, THIRD_EVAL_NAME}</b>&lt;/pattern></pre>
    
    <p>If the option includes special characters such as a braces, spaces or
    commas, you can enclose it between single or double quotes. For
    example, consider the next pattern.</p>

		<pre class="prettyprint source">&lt;pattern>%-5level - %replace(%msg)<b>{'\d{14,16}', 'XXXX'}</b>%n&lt;/pattern></pre>


    <p>We pass the options <code>\d{16}</code> and <code>XXXX</code>
    to the <code>replace</code> conversion word. It replaces any
    sequence of 14, 15 or 16 digits contained in the message with XXXX
    effectively obfuscating credit card numbers. Note that "\d" which
    is a shorthand for a single digit in regular expressions. The
    "{14,16\}" is interpreted as "{14, 16}", that is, repeat the
    previous item at least 14 but at most 16 times.
    </p>

    <h2 class="doAnchor" name="grouping">Grouping with
      parentheses</h2>

    <p>In logback, parentheses within the pattern string are treated
    as grouping tokens. Thus, it is possible to group a sub-pattern
    and apply formatting directives on that sub-pattern. 
    </p>

    <p>For example, the pattern</p> 

    <p class="source"><b>%-30(</b>%d{HH:mm:ss.SSS} [%thread]<b>)</b> %-5level %logger{32} - %msg%n</p> 

    <p>will group the output generated by the sub-pattern
    "%d{HH:mm:ss.SSS} [%thread]" so that it is right-padded if less
    than 30 characters.
    </p>

    <p>Assuming without the grouping the output was</p>

    <p class="source">13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Classload hashcode is 13995234
13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Initializing for ServletContext
13:09:30 [main] DEBUG c.q.logback.demo.ContextListener - Trying platform Mbean server
13:09:30 [pool-1-thread-1] INFO  ch.qos.logback.demo.LoggingTask - Howdydy-diddly-ho - 0
13:09:38 [btpool0-7] INFO c.q.l.demo.lottery.LotteryAction - Number: 50 was tried.
13:09:40 [btpool0-7] INFO c.q.l.d.prime.NumberCruncherImpl - Beginning to factor.
13:09:40 [btpool0-7] DEBUG c.q.l.d.prime.NumberCruncherImpl - Trying 2 as a factor.
13:09:40 [btpool0-7] INFO c.q.l.d.prime.NumberCruncherImpl - Found factor 2
    </p>

    <p>with the "%-30()" grouping it would be</p>

    <p class="source">13:09:30 [main]            DEBUG c.q.logback.demo.ContextListener - Classload hashcode is 13995234
13:09:30 [main]            DEBUG c.q.logback.demo.ContextListener - Initializing for ServletContext
13:09:30 [main]            DEBUG c.q.logback.demo.ContextListener - Trying platform Mbean server
13:09:30 [pool-1-thread-1] INFO  ch.qos.logback.demo.LoggingTask - Howdydy-diddly-ho - 0
13:09:38 [btpool0-7]       INFO  c.q.l.demo.lottery.LotteryAction - Number: 50 was tried.
13:09:40 [btpool0-7]       INFO  c.q.l.d.prime.NumberCruncherImpl - Beginning to factor.
13:09:40 [btpool0-7]       DEBUG c.q.l.d.prime.NumberCruncherImpl - Trying 2 as a factor.
13:09:40 [btpool0-7]       INFO  c.q.l.d.prime.NumberCruncherImpl - Found factor 2
    </p>

    
    <p>The latter form is more comfortable to read.</p>
    
    <p>If you need to treat the parenthesis character as a literal, it
    needs to be escaped by preceding each parenthesis with a
    backslash. As in, <b>\(</b>%d{HH:mm:ss.SSS}
    [%thread]<b>\)</b>. 
    </p>

    <h2 class="doAnchor" name="coloring">Coloring</h2>

    <p>Grouping by <a href="#Parentheses">parentheses</a> as explained
    above allows coloring of sub-patterns. As of version 1.0.5,
    <code>PatternLayout</code> recognizes "%black", "%red",
    "%green","%yellow","%blue", "%magenta","%cyan", "%white", "%gray",
    "%boldRed","%boldGreen", "%boldYellow", "%boldBlue",
    "%boldMagenta""%boldCyan", "%boldWhite" and "%highlight" as
    conversion words. These conversion words are intended to contain a
    sub-pattern. Any sub-pattern enclosed by a coloring word will be
    output in the specified color.
    </p>

    <p>Below is a configuration file illustrating coloring. Note the
    %cyan conversion specifier enclosing "%logger{15}". This will
    output the logger name abbreviated to 15 characters in cyan. The
    %highlight conversion specifier prints its sub-pattern in bold-red
    for events of level ERROR, in red for WARN, in BLUE for INFO, and
    in the default color for other levels.</p>

		<em>
			Example: Highlighting levels
			(logback-examples/src/main/resources/chapters/layouts/highlighted.xml)
		</em>


<pre id="highlighted" class="prettyprint">&lt;configuration debug="true">
  &lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <b>&lt;withJansi>true&lt;/withJansi></b>
    &lt;encoder>
      &lt;pattern>[%thread] <b>%highlight(%-5level)</b> <b>%cyan(%logger{15})</b> - %msg %n&lt;/pattern>
    &lt;/encoder>
  &lt;/appender>
  &lt;root level="DEBUG">
    &lt;appender-ref ref="STDOUT" />
  &lt;/root>
&lt;/configuration></pre>

     <p>Setting <code>withJansi</code> to true enables ANSI
     color code interpretation by the Jansi library, which transparently
     filters out ANSI escape sequences if the underlying terminal is not
     compatible. This is the safest choice for cross-platform deployments,
     but requires org.fusesource.jansi:jansi:1.17 or higher on the class path.
     Note that Unix-based operating systems such as Linux and Mac OS X
     support ANSI color codes natively and usually do not require
     enabling the Jansi library, but doing so is harmless.
     On Windows however, enabling Jansi is recommended to benefit from color
     code interpretation on DOS command prompts, which otherwise
     risk being sent ANSI escape sequences that they cannot interpret.
     </p>

     <p>Here is the corresponding output:</p>

<pre class="source">[main] <span style="color:#611">WARN</span>  <span style="color:#2bd">c.l.TrivialMain</span> - a warning message 0
[main] DEBUG <span style="color:#2bd">c.l.TrivialMain</span> - hello world number1
[main] DEBUG <span style="color:#2bd">c.l.TrivialMain</span> - hello world number2
[main] <span style="color:#00F">INFO</span>  <span style="color:#2bd">c.l.TrivialMain</span> - hello world number3
[main] DEBUG <span style="color:#2bd">c.l.TrivialMain</span> - hello world number4
[main] <span style="color:#611">WARN</span>  <span style="color:#2bd">c.l.TrivialMain</span> - a warning message 5
[main] <span style="color:#F00">ERROR</span> <span style="color:#2bd">c.l.TrivialMain</span> - Finish off with fireworks</pre>

    <p>It takes very few lines of code to create a coloring conversion
    word. The section entitled <a
    href="#customConversionSpecifier">creating a custom conversion
    specifier</a> discusses the steps necessary for registering a
    conversion word in your configuration file.</p>
   
		<h2 class="doAnchor" name="Evaluators">Evaluators</h2>

		<p>As mentioned above, option lists come in handy when a
		conversion specifier is required to behave dynamically based on
		one or more
		<a href="../xref/ch/qos/logback/core/boolex/EventEvaluator.html">
		<code>EventEvaluator</code></a> objects.
		<code>EventEvaluator</code> objects have the responsibility to
		determine whether a given logging event matches the criteria of the
		evaluator.
		</p>
		
    <p>Let us review an example involving a
    <code>EventEvaluator</code>.  The next configuration file outputs
    the logging events to the console, displaying date, thread, level,
    message and caller data. Given that extracting the caller data of
    a logging event is on the expensive side, we will do so only when
    the logging request originates from a specific logger, and when
    the message contains a certain string. Thus, we make sure that only
    specific logging requests will have their caller information
    generated and displayed. In other cases, where the caller data is
    superfluous, we will not penalize application performance.
		</p>

    <p>Evaluators and in particular <em>evaluation expressions</em>
    are presented in a <a
    href="filters.html#evalutatorFilter">dedicated section of the
    chapter on filters</a> which you MUST read if you want to use
    evaluators in any meaningful way. Also note that the examples below
    are implicitly based on <code>JaninoEventEvaluator</code> which
    requires the <a
    href="http://docs.codehaus.org/display/JANINO/Home">Janino
    library</a>. Please see the <a
    href="../setup.html#janino">corresponding section</a> of the setup
    document.</p>

		<em>
			Example: Sample usage of EventEvaluators
			(logback-examples/src/main/resources/chapters/layouts/callerEvaluatorConfig.xml)
		</em>


		<pre id="callerEvaluatorConfig" class="prettyprint source">&lt;configuration>
  <b>&lt;evaluator name="DISP_CALLER_EVAL">
    &lt;expression>logger.contains("chapters.layouts") &amp;amp;&amp;amp; \
      message.contains("who calls thee")&lt;/expression>
  &lt;/evaluator></b>

  &lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> 
    &lt;encoder>
      &lt;pattern>
        %-4relative [%thread] %-5level - %msg%n<b>%caller{2, DISP_CALLER_EVAL}</b>
      &lt;/pattern>
    &lt;/encoder>
  &lt;/appender>

  &lt;root level="DEBUG"> 
    &lt;appender-ref ref="STDOUT" /> 
  &lt;/root>
&lt;/configuration></pre>

		<p>The above evaluation expression matches events which emanate
		from a logger with a name containing the string "chapters.layouts"
		and the message contains the string "who calls thee". Due to XML
		encoding rules, the &amp; character cannot be written as is, and
		needs to be escaped as &amp;amp;.</p>

    <p>The following class makes use of some of the characteristics
    mentioned in above configuration file.</p>
		
    <p><em>
			Example: Sample usage of EventEvaluators
			<a href="../xref/chapters/layouts/CallerEvaluatorExample.html">
			(logback-examples/src/main/java/chapters/layouts/CallerEvaluatorExample.java)</a>
		</em>
    </p>
		<pre class="prettyprint source">package <b>chapters.layouts</b>;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;

public class CallerEvaluatorExample {

  public static void main(String[] args)  {
    Logger logger = LoggerFactory.getLogger(CallerEvaluatorExample.class);
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

    try {
      JoranConfigurator configurator = new JoranConfigurator();
      configurator.setContext(lc);
      configurator.doConfigure(args[0]);
    } catch (JoranException je) {
      // StatusPrinter will handle this
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(lc);

    for (int i = 0; i &lt; 5; i++) {
      if (i == 3) {
        logger.debug(<b>"who calls thee</b>?");
      } else {
        logger.debug("I know me " + i);
      }
    }
  }
}</pre>

		<p>The above application does nothing particularly fancy. Five
		logging requests are issued, the third one emitting the message
		"who calls thee?"
		</p>

		<p>The command</p>

    <p class="source">java chapters.layouts.CallerEvaluatorExample src/main/java/chapters/layouts/callerEvaluatorConfig.xml</p>

    <p>will yield</p>

		<div class="source"><pre>0    [main] DEBUG - I know me 0 
0    [main] DEBUG - I know me 1 
0    [main] DEBUG - I know me 2 
0    [main] DEBUG - who calls thee? 
Caller+0   at chapters.layouts.CallerEvaluatorExample.main(CallerEvaluatorExample.java:28)
0    [main] DEBUG - I know me 4</pre></div>


		<p>When a logging request is issued, the corresponding logging
		event is evaluated. Only the third logging event matches the
		evaluation criteria, causing its caller data to be displayed. For
		other logging events, the evaluation criteria do not match and no
		caller data is printed.
		</p>


		<p>One can change the expression to correspond a real world
		scenario. For instance, one could combine the logger name and
		request level. Thus, logging requests of level <em>WARN</em> and
		up, originating from a sensitive part of an application, e.g. a
		financial transaction module, would have their caller data
		displayed.
		</p>

		<p><b>Important:</b> With the <em>caller</em> conversion word,
		caller data is output when <em>the expression evaluates to
		<b>true</b>.</em></p>

		<p>Let us consider at a different situation. When exceptions are
		included in a logging request, their stack trace is also
		output. However, one might want to suppress the stack trace for
		some specific exceptions.
		</p>

		<p>The Java code shown below creates three log requests, each with
		an exception. The second exception is different from the others:
		it contains the string "do not display this" and it is of type
		<code>chapters.layouts.TestException</code>. As its message
		commands, let us now prevent the second exception from being
		printed.</p>

   <p><em>
			Example: Sample usage of EventEvaluators
			<a href="../xref/chapters/layouts/ExceptionEvaluatorExample.html">
			(logback-examples/src/main/java/chapters/layouts/ExceptionEvaluatorExample.java)</a>
		</em>
    </p>
<pre class="prettyprint source">package chapters.layouts;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;

public class ExceptionEvaluatorExample {

  public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(ExceptionEvaluatorExample.class);
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

    try {
      JoranConfigurator configurator = new JoranConfigurator();
      configurator.setContext(lc);
      lc.reset();
      configurator.doConfigure(args[0]);
    } catch (JoranException je) {
       // StatusPrinter will handle this
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(lc);

    for (int i = 0; i &lt; 3; i++) {
      if (i == 1) {
        logger.debug("logging statement " + i, new TestException(
            "do not display this"));
      } else {
        logger.debug("logging statement " + i, new Exception("display"));
      }
    }
  }
}</pre>
		
		<p>In the next configuration file, the evaluation expression
		matches events containing a throwable of type
		<code>chapters.layouts.TextException</code>, precisely the type of
		exceptions we wish to suppress.
    </p>

		<em>
			Example: Sample usage of EventEvaluators
			(logback-examples/src/main/resources/chapters/layouts/exceptionEvaluatorConfig.xml)
		</em>
		<pre class="prettyprint source">&lt;configuration>

  <b>&lt;evaluator name="DISPLAY_EX_EVAL">
    &lt;expression>throwable != null &amp;amp;&amp;amp; throwable instanceof  \
      chapters.layouts.TestException&lt;/expression>
  &lt;/evaluator></b>
	
  &lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    &lt;encoder>
      &lt;pattern>%msg%n<b>%ex{full, DISPLAY_EX_EVAL}</b>&lt;/pattern>
    &lt;/encoder>
  &lt;/appender>

  &lt;root level="debug">
    &lt;appender-ref ref="STDOUT" />
  &lt;/root>
&lt;/configuration></pre>

		<p>With this configuration, each time an instance of the
		<em>chapters.layouts.TestException</em> is included within a logging
		request, the stack trace will be suppressed.
		</p>

    <p>Launching the command</p>

    <p class="source">java chapters.layouts.ExceptionEvaluatorExample src/main/java/chapters/layouts/exceptionEvaluatorConfig.xml</p>

    <p>will yield</p>

<p class="source">logging statement 0
java.lang.Exception: display
  at chapters.layouts.ExceptionEvaluatorExample.main(ExceptionEvaluatorExample.java:43) [logback-examples-0.9.19.jar:na]
logging statement 1
logging statement 2
java.lang.Exception: display
  at chapters.layouts.ExceptionEvaluatorExample.main(ExceptionEvaluatorExample.java:43) [logback-examples-0.9.19.jar:na]</p>


    <p>Notice how the second log statement has no stack trace. We
    effectively suppressed the stack trace for the
    <code>TextException</code>. The text between square brackets at
    the end of each stack trace line is <a
    href="#xThrowable">packaging information</a> discussed
    earlier.</p>

		<p><span class="label notice">Note</span> With the <b><em>%ex</em></b> conversion
		specifier, the stack trace is displayed when <em>the expression
		evaluates to <b>false</b>.</em></p>


    
		<h2 class="doAnchor" name="customConversionSpecifier">Creating a
		custom conversion specifier</h2>

		<p>Up to this point we have presented the built-in conversion
		words in <code>PatternLayout</code>. But it is also possible to
		add conversion words of your own making.</p>
		
		<p>Building a custom conversion specifier consists of two steps.
    </p>
		
    <h4>Step 1</h4>

		<p>First, you must extend the <code>ClassicConverter</code>
		class. <a
		href="../xref/ch/qos/logback/classic/pattern/ClassicConverter.html">
		<code>ClassicConverter</code></a> objects are responsible for
		extracting information out of <code>ILoggingEvent</code> instances
		and producing a String. For example,
		<a href="../xref/ch/qos/logback/classic/pattern/LoggerConverter.html">
		<code>LoggerConverter</code></a>, the converter underlying the
		%logger conversion word, extracts the name of the logger from 
		<code>ILoggingEvent</code> and returns it as a String. It might
		abbreviate the logger name in the process.</p>
		
		<p>Here is a customer converter which returns the time elapsed
		since its creaton in nanoseconds:</p>
		
<em> Example: Sample Converter Example 
<a href="../xref/chapters/layouts/MySampleConverter.html">
(src/main/java/chapters/layouts/MySampleConverter.java)</a></em>
<pre class="prettyprint source">public class MySampleConverter extends ClassicConverter {

  long start = System.nanoTime();

  <b>@Override</b>
  <b>public String convert(ILoggingEvent event) {</b>
    <b>long nowInNanos = System.nanoTime();</b>
    <b>return Long.toString(nowInNanos-start);</b>
  <b>}</b>
}</pre>

		<p>This implementation is pretty straightforward. The
		<code>MySampleConverter</code> class extends
		<code>ClassicConverter</code>, and implements the
		<code>convert</code> method which returns the number of
		nano-seconds elapsed since its creation.
		</p>

    <h4>Step 2</h4>

		<p>In the second step, we must let logback know about the new
		<code>Converter</code>. For this purpose, we need to declare the
		new conversion word in the configuration file, as shown below:</p>
		
<em> Example: Sample Converter Example (src/main/java/chapters/layouts/mySampleConverterConfig.xml)</em>

<pre id="mySampleConverterConfig" class="prettyprint source">&lt;configuration>

  <b>&lt;conversionRule conversionWord="nanos" 
                  converterClass="chapters.layouts.MySampleConverter" /></b>
	
  &lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    &lt;encoder>
      &lt;pattern><b>%-6nanos</b> [%thread] - %msg%n&lt;/pattern>
    &lt;/encoder>
  &lt;/appender>

  &lt;root level="DEBUG">
    &lt;appender-ref ref="STDOUT" />
  &lt;/root>
&lt;/configuration></pre>

		<p>Once the new conversion word has been declared in the
		configuration file, we can refer to it within
		<code>PatternLayout</code> pattern, as with any other
		conversion word.</p>
		
    <p>The command:</p>

    <div class="source">java chapters.layouts.SampleLogging src/main/java/chapters/layouts/mySampleConverterConfig.xml </div>

    <p>should yield output akin to:</p>
    
    <pre class="source">4868695 [main] DEBUG - Everything's going well
5758748 [main] ERROR - maybe not quite...</pre>


		<p>The reader might want to take a look at other
		<code>Converter</code> implementations such as
		<a href="../xref/ch/qos/logback/classic/pattern/MDCConverter.html">
		<code>MDCConverter</code></a> to learn about more complex
		behaviours, such as option handling. For creating your own
		coloring schemes have a look at <a
		href="../xref/ch/qos/logback/classic/pattern/color/HighlightingCompositeConverter.html"><code>HighlightingCompositeConverter</code></a>.
		</p>

   	

    <h2 class="doAnchor" name="ClassicHTMLLayout">HTMLLayout</h2>
	
	  <p><a
	  href="../xref/ch/qos/logback/classic/html/HTMLLayout.html"><code>HTMLLayout</code></a>
	  (as included in logback-classic) generates logs in HTML
	  format. <code>HTMLLayout</code> outputs logging events in an HTML
	  table where each row of the table corresponds to a logging
	  event.</p>
		
		<p>Here is a sample output produced by <code>HTMLLayout</code>
		using its default CSS stylesheet:</p>
		<img src="images/chapters/layouts/htmlLayout0.gif" alt="HTML Layout Sample Image"/>
		
		<p>The content of table columns are specified with the help of a
		conversion pattern. See <a
		href="#ClassicPatternLayout"><code>PatternLayout</code></a> for
		documentation on conversion patterns. As such, you have full
		control over the contents and format of the table. You can select
		and display any combination of converters
		<code>PatternLayout</code> knows about.
		</p>

		<p>One notable exception about the use of
		<code>PatternLayout</code> with <code>HTMLLayout</code> is that
		conversion specifiers should not be separated by space characters
		or more generally by literal text. Each specifier found in the
		pattern will result in a separate column.  Likewise a separate
		column will be generated for each block of literal text found in
		the pattern, potentially wasting valuable real-estate on your
		screen.</p>
     
    <p>Here is simple but functional configuration file illustrating
    the use of <code>HTMLLayout</code>.
    </p>

<em> Example: HTMLLayout Example (src/main/java/chapters/layouts/htmlLayoutConfig1.xml)</em>

<pre id="htmlLayoutConfig1" class="prettyprint source">&lt;configuration debug="true"&gt;
  &lt;appender name="FILE" class="ch.qos.logback.core.FileAppender"&gt;
    &lt;encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
      &lt;layout class="ch.qos.logback.classic.html.HTMLLayout">
        <b>&lt;pattern&gt;%relative%thread%mdc%level%logger%msg&lt;/pattern&gt;</b>
      &lt;/layout&gt;
    &lt;/encoder>
    &lt;file>test.html&lt;/file&gt;
  &lt;/appender&gt;

  &lt;root level="DEBUG">
    &lt;appender-ref ref="FILE" />
  &lt;/root>
&lt;/configuration>
</pre>

   <p>The <a
   href="../xref/chapters/layouts/TrivialMain.html">TrivialMain</a>
   application logs a few messages finishing with an exception. The
   command:</p>

   <p class="source">java chapters.layouts.TrivialMain src/main/java/chapters/layouts/htmlLayoutConfig1.xml</p>

    <p>will create the file <em>test.html</em> in the current
    folder. The contents of <em>test.html</em> should be similar to:
		</p>
		<img src="images/chapters/layouts/htmlLayout1.png" alt="HTML Layout Sample Image"/>

    <h3>Stack traces</h3>

		<p> If you use the <em>%em</em> conversion word to display stack
		traces, a table column will be created to display stack traces. In
		most cases the column will be empty, wasting screen
		real-estate. Moreover, printing a stack trace on a separate column
		does not yield very readable results. Fortunately, the
		<em>%ex</em> conversion word is not the only way to display stack
		traces.
		</p>

		<p>A better solution is available through implementations of
		<code>IThrowableRenderer</code> interface.  Such an implementation
		can be assigned to <code>HTMLLayout</code> to manage the display
		data related to exceptions. By default, a
		<a href="../xref/ch/qos/logback/classic/html/DefaultThrowableRenderer.html">
			<code>DefaultThrowableRenderer</code></a> is assigned to each
			<code>HTMLLayout</code> instance. It writes exceptions on a
			<em>new table row</em>, along with its stack trace, in an easily
			readable manner, as shown on the figure above.
		</p>

		<p>If for some reason, you still wish to use the <em>%ex</em>
		pattern, then you can specify <a
		href="../xref/ch/qos/logback/core/html/NOPThrowableRenderer.html">
		<code>NOPThrowableRenderer</code></a> in the configuration file in
		order to disable displaying a separate row for the stack trace. We
		don't have the faintest idea why you would want to do that, but if
		you wished, you could.
		</p>

    <h3>CSS</h3>

    <p>The presentation of the HTML created by <code>HTMLLayout</code>
    is controlled through a Cascading Style Sheet (CSS). In the
    absence of specific instructions, <code>HTMLLayout</code> will
    default to its internal CSS. However, you can instruct
    <code>HTMLLayout</code> to use an external CSS file. For this
    purpose a <code>cssBuilder</code> element can be nested within a
    <code>&lt;layout&gt;</code> element, as shown below.
		</p>

<pre class="prettyprint source">&lt;layout class="ch.qos.logback.classic.html.HTMLLayout">
  &lt;pattern>%relative...%msg&lt;/pattern>
  &lt;cssBuilder class="ch.qos.logback.classic.html.UrlCssBuilder">
    &lt;!-- url where the css file is located --&gt;
    &lt;url>http://...&lt;/url>
  &lt;/cssBuilder>	
&lt;/layout></pre>

	
		<p>The <code>HTMLLayout</code> is often used in conjunction with
		<code>SMTPAppender</code> so that outgoing email is pleasantly
		formatted in HTML.
		</p>


    <h2 class="doAnchor" name="log4jXMLLayout">Log4j XMLLayout</h2>

    <p><a
    href="../xref/ch/qos/logback/classic/log4j/XMLLayout.html">XMLLayout</a>
    (part of logback-classic) generates output in a log4j.dtd
    compliant format to interoperate with tools such as <a
    href="http://logging.apache.org/chainsaw/index.html">Chainsaw</a>
    and <a href="http://vigilog.sourceforge.net/">Vigilog</a> capable
    of processing files generated by <a
    href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/XMLLayout.html">log4j's
    XMLLayout</a>.
    </p>


    <p>As the original XMLLayout in log4j version 1.2.15, XMLLayout in
    logback-classic takes two boolean properties, <span
    class="option">locationInfo</span> and <span
    class="option">properties</span>. Setting <span
    class="option">locationInfo</span> to true enables the inclusion
    of location info (caller data) in the each event. Setting <span
    class="option">properties</span> to true enables the inclusion of
    MDC information. Both options are set to false by default.
    </p>

    <p>Here is a sample configuration</p>

<em> Example: Log4jXMLLayout Example (src/main/java/chapters/layouts/log4jXMLLayout.xml)</em>

    <pre id="log4jXMLLayout" class="prettyprint source">&lt;configuration>
  &lt;appender name="FILE" class="ch.qos.logback.core.FileAppender">
    &lt;file>test.xml&lt;/file>
    &lt;encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
      &lt;layout class="ch.qos.logback.classic.log4j.XMLLayout">
        &lt;locationInfo>true&lt;/locationInfo>
      &lt;/layout>
    &lt;/encoder> 
  &lt;/appender> 

  &lt;root level="DEBUG">
    &lt;appender-ref ref="FILE" />
  &lt;/root>
&lt;/configuration> </pre>
    
		<h1 class="doAnchor" name="logback-access">Logback access</h1>

		<p>Most logback-access layouts are mere adaptations of
		logback-classic layouts. Logback-classic and logback-access
		modules address different needs, but in general offer comparable
		functionality.</p>
		
		<h2>Writing your own Layout</h2>

		<p>Writing a custom <code>Layout</code> for logback access is
		nearly identical to its sibling <code>Layout</code> in
		logback-classic.</p>
		

		<h3 class="doAnchor" name="AccessPatternLayout">PatternLayout</h3>

		<p><a href="../xref/ch/qos/logback/access/PatternLayout.html">
		<code>PatternLayout</code></a> in logback-access can be configured
		in much the same way as its classic counterpart. However it
		features additional conversion specifiers suited for logging
		particular bits of information available only in HTTP servlet
		requests and HTTP servlet responses.
    </p>

		<p>Below is a list of conversion specifiers for 
		<code>PatternLayout</code> in logback-access.</p>
		
		<table  class="bodyTable striped" border="0" cellpadding="8">
      <tr>
        <th align="center">Conversion Word</th>
        <th align="center">Effect</th>
      </tr>
      <tr>
        <td class="word" name="remoteIP">
          <b>a / remoteIP</b>
        </td>
        <td>
          <p>Remote IP address.</p>
        </td>
      </tr>
      <tr>
        <td class="word" name="localIP"><b>A / localIP</b></td>
        <td>
          <p>Local IP address.</p>
        </td>
      </tr>		
      <tr>
        <td class="word" name="bytesSent"><b>b / B / bytesSent</b></td>
        <td>
          <p>
            Response's content length.
          </p>
        </td>
      </tr>				
      <tr>
        <td class="word" name="clientHost"><b>h / clientHost</b></td>
        <td>
          <p>
            Remote host.
          </p>
        </td>
      </tr>
      <tr>
        <td class="word" name="protocol"><b>H / protocol</b></td>
        <td>
          <p>Request protocol.</p>
        </td>
      </tr>
      <tr>
        <td class="word" name="remoteLogName"><b>l</b></td>
        <td>
          <p>
            Remote log name. In logback-access, this converter always
            returns the value "-".
          </p>
        </td>
      </tr>
      
      <tr>
        <td class="word" name="reqParameter"><b>reqParameter{paramName}</b></td>
        <td>
          <p>Parameter of the response.</p>
          <p>This conversion word takes the first option in braces and looks
          for the corresponding parameter in the request.</p>
          <p><b>%reqParameter{input_data}</b> 
          displays the corresponding parameter.</p>
        </td>
      </tr>		
      <tr>
        <td class="word" name="header"><b>i{header} / header{header}</b></td>
        <td>
          <p>Request header.</p>
          <p>This conversion word takes the first option in braces and looks
          for the corresponding header in the request.</p>
          <p><b>%header{Referer}</b> displays the referer of the request.</p>
          <p>
            If no option is specified, it displays every available header.
          </p>
        </td>
      </tr>	
      <tr >
        <td class="word" name="requestMethod"><b>m / requestMethod</b></td>
        <td>
          <p>Request method.</p>
        </td>
      </tr>		
      <tr>
        <td class="word" name="requestURL"><b>r / requestURL</b></td>
        <td>
          <p>
            URL requested.
          </p>
        </td>
      </tr>
      <tr>
        <td class="word" name="statusCode"><b>s / statusCode</b></td>
        <td>
          <p>
            Status code of the request.
          </p>
        </td>
      </tr>
      <tr>
          <td class="word" name="elapsedTime"><b>D / elapsedTime</b></td>
          <td>
              <p>
                  The time taken to serve the request, in milliseconds.
              </p>
          </td>
      </tr>
      <tr>
        <td class="word" name="elapsedSeconds"><b>T / elapsedSeconds</b></td>
        <td>
          <p>
            The time taken to serve the request, in seconds.
          </p>
        </td>
      </tr>
      <tr>
        <td class="word" name="dateAccess"><b>t / date</b></td>
        <td>
          <p>Outputs the date of the logging event.  The date
          conversion specifier may be followed by a set of braces
          containing a date and time pattern strings used by
          <code>java.text.SimpleDateFormat</code>.  <em>ISO8601</em>
          is also a valid value.
					</p>
					<p>For example, <b>%t{HH:mm:ss,SSS}</b> or
					<b>%t{dd&nbsp;MMM&nbsp;yyyy&nbsp;;HH:mm:ss,SSS}</b>.
					If no date format specifier is given then the
					Common Log Format date format is assumed, that is: <b>%t{dd/MMM/yyyy:HH:mm:ss&nbsp;Z}</b>
					</p>
        </td>
      </tr>
      <tr>
        <td class="word" name="httpUser"><b>u / user</b></td>
        <td>
          <p>
            Remote user.
          </p>
        </td>
      </tr>		
      <tr>
        <td class="word" name="queryString"><b>q / queryString</b></td>
        <td>
          <p>
            Request query string, prepended with a '?'.
          </p>
        </td>
      </tr>
      <tr>
        <td class="word" name="requestURI"><b>U / requestURI</b></td>
        <td>
          <p>
            Requested URI.
          </p>
        </td>
      </tr>		
      <tr>
        <td class="word" name="sessionID"><b>S / sessionID</b></td>
        <td>
          <p>Session ID.</p>
        </td>
      </tr>
      <tr >
        <td class="word" name="server"><b>v / server</b></td>
        <td>
          <p>Server name.</p>
        </td>
      </tr>
      <tr>
        <td class="word" name="threadName"><b>I / threadName</b></td>
        <td>
          <p>Name of the thread which processed the request.</p>
        </td>
      </tr>
      <tr class="b">
        <td class="word" name="localPort"><b>localPort</b></td>
        <td>
          <p>Local port.</p>
        </td>
      </tr>
      <tr class="a">
        <td class="word" name="reqAttribute"><b>reqAttribute{attributeName}</b></td>
        <td>
          <p>Attribute of the request.</p>
          <p>This conversion word takes the first option in braces and looks
          for the corresponding attribute in the request.</p>
          <p><b>%reqAttribute{SOME_ATTRIBUTE}</b> 
          displays the corresponding attribute.</p>
        </td>
      </tr>
      <tr class="b">
        <td class="word" name="reqCookie"><b>reqCookie{cookie}</b></td>
        <td>
          <p>Request cookie.</p>
          <p>This conversion word takes the first option in braces and looks
          for the corresponding cookie in the request.</p>
          <p><b>%cookie{COOKIE_NAME}</b> displays corresponding cookie.</p>
        </td>
      </tr>
      <tr class="a">
        <td class="word" name="responseHeader"><b>responseHeader{header}</b></td>
        <td>
          <p>
            Header of the response.
          </p>
          <p>This conversion word takes the first option in braces and looks
          for the corresponding header in the response.</p>
          <p><b>%header{Referer}</b> displays the referer of the response.</p>
        </td>
      </tr>
      <tr class="b">
        <td class="word" name="requestContent"><b>requestContent</b></td>
        <td>
          <p>This conversion word displays the content of the request,
          that is the request's <code>InputStream</code>. It is used
          in conjunction with a <a
          href="../xref/ch/qos/logback/access/servlet/TeeFilter.html">
          <code>TeeFilter</code></a>, a
          <code>javax.servlet.Filter</code> that replaces the original
          <code>HttpServletRequest</code> by a <a
          href="../xref/ch/qos/logback/access/servlet/TeeHttpServletRequest.html">
          <code>TeeHttpServletRequest</code></a>. The latter object
          allows access to the request's <code>InputStream</code>
          multiple times without any loss of data.
          </p>
        </td>
      </tr>
      <tr class="a">
        <td class="word" name="fullRequest"><b>fullRequest</b></td>
        <td>
          <p>This converter outputs the data associated with the
          request, including all headers and request contents.
          </p>
        </td>
      </tr>
      <tr class="b">
        <td class="word" name="responseContent"><b>responseContent</b></td>
        <td>
          <p>This conversion word displays the content of the
          response, that is the response's
          <code>InputStream</code>. It is used in conjunction with a
          <a href="../xref/ch/qos/logback/access/servlet/TeeFilter.html">
          <code>TeeFilter</code></a>, a
          <code>javax.servlet.Filter</code> that replaces the original
          <code>HttpServletResponse</code> by a <a
          href="../xref/ch/qos/logback/access/servlet/TeeHttpServletResponse.html">
          <code>TeeHttpServletResponse</code></a>. The latter object
          allows access to the request's <code>InputStream</code>
          multiple times without any loss of data.
          </p>
        </td>
      </tr>
      <tr class="a">
        <td class="word" name="fullResponse"><b>fullResponse</b></td>
        <td>
          <p>This conversion word takes all the available data
          associated with the response, including all headers of the
          response and response contents.
          </p>
        </td>
      </tr>
    </table>
		
		<p>Logback access' <code>PatternLayout</code> also recognizes three keywords, which
		act like shortcuts.</p>

    <table  class="bodyTable">
      <tr>
        <th>keyword</th>
        <th>equivalent conversion pattern</th>
      </tr>
      <tr class="a">
        <td><em>common</em> or <em>CLF</em></td>
        <td><em>%h %l %u [%t] "%r" %s %b</em></td>
      </tr>
      <tr class="b">
        <td><em>combined</em></td>
        <td><em>%h %l %u [%t] "%r" %s %b "%i{Referer}" "%i{User-Agent}"</em></td>
      </tr>

    </table>

 	
	 	<p>The <em>common</em> keyword corresponds to the pattern <em>'%h %l %u [%t] "%r" %s %b'</em>
	 	which displays client host, remote log name, user, date, requested URL, status code 
	 	and response's content length</p>
	 	
	 	<p>The <em>combined</em> keyword is a shortcut for <em>'%h %l %u [%t]
	 	"%r" %s %b "%i{Referer}" "%i{User-Agent}"'</em>. This pattern
	 	begins much like the <em>common</em> pattern but also displays two
	 	request headers, namely referer, and user-agent.</p>

		<h3 class="doAnchor" name="AccessHTMLLayout">HTMLLayout</h3>
		
		<p>The <a
		href="../xref/ch/qos/logback/access/html/HTMLLayout.html"><code>HTMLLayout</code></a>
		class found in logback-access is similar to the <a
		href="#ClassicHTMLLayout"><code>HTMLLayout</code></a> class from
		logback-classic.
    </p>
		
		<p>By default, it will create a table containing the following data:</p>
		
		<ul>
			<li>Remote IP</li>
			<li>Date</li>
			<li>Request URL</li>
			<li>Status code</li>
			<li>Content Length</li>
		</ul>
		
		<p>Here is a sample output produced by <code>HTMLLayout</code> in
		logback-access:</p>
		<img src="images/chapters/layouts/htmlLayoutAccess.gif" alt="Access HTML Layout Sample Image"/>

		<p>What can be better than a real world example? Our own log4j
		properties for logback <a
		href="http://logback.qos.ch/translator/">translator</a> makes use
		of logback-access to demonstrate live output from
		<code>RollingFileAppender</code> with <code>HTMLLayout</code>.</p>


    <p>On every new user request to our <a
    href="http://logback.qos.ch/translator/">translator</a>
    web-application, a new entry will be added to the access logs,
    which you can view by <a
    href="http://logback.qos.ch/translator/logs/access.html">following
    this link</a>.</p>


    <script src="../templates/footer.js" type="text/javascript"></script>

    
                </div>
                </div>
</body>
</html>
